<template>
  <el-dialog :title="!dataForm.id ? $t('Common.Add') : $t('Common.Edit')" :close-on-click-modal="false" :visible.sync="visible" class="hotel-room">
    <el-form :model="dataForm" :disabled="dataForm.trialPictureState == 1" :rules="dataRule" ref="dataForm" @keyup.enter.native="dataFormSubmit()" label-width="auto">
      
      <el-form-item label-width="0" v-if="dataForm.trialPictureState == 1">
        <el-alert
          title="待审核"
          type="warning"
          show-icon>
        </el-alert>
      </el-form-item>
      <el-form-item label-width="0" v-if="dataForm.trialPictureState == 3">
        <el-alert
          show-icon
          title="审核失败"
          type="warning"
          :description="dataForm.trialMsg">
        </el-alert>
      </el-form-item>
      
      <el-form-item label="房型名字" prop="name"><el-input v-model="dataForm.name" placeholder="房型名字"></el-input></el-form-item>
<!--      <el-form-item label="房间类别" prop="classify">
        <el-radio-group v-model="dataForm.classify">
          <el-radio :label="1">全天房</el-radio>
          <el-radio :label="0">钟点房</el-radio>
        </el-radio-group>
      </el-form-item> -->


      <el-form-item label="房型类别" prop="checkList">
        <el-checkbox-group v-model="dataForm.checkList">
            <el-checkbox label="全天房"></el-checkbox>
            <el-checkbox label="钟点房"></el-checkbox>
          </el-checkbox-group>
      </el-form-item>

      <el-form-item label="门市价" prop="price"><el-input v-model="dataForm.oprice" placeholder="门市价"></el-input></el-form-item>
      <el-form-item label="房型标签" prop="discounts">
        <el-tag :key="tag" v-for="tag in dataForm.tagList" closable :disable-transitions="false" @close="handleClose(tag)">{{ tag }}</el-tag>
        <el-input class="input-new-tag" v-if="inputVisible" v-model="inputValue" ref="saveTagInput" size="small">
          <el-button slot="append" icon="el-icon-plus" @click="handleInputConfirm()"></el-button>
        </el-input>
        <el-button v-else class="button-new-tag" size="small" @click="showInput">添加</el-button>
      </el-form-item>
      <el-form-item label="房型大图" prop="logo">
        <el-upload class="avatar-uploader" :action="uploadAction" :show-file-list="false" :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
          <img v-if="dataForm.logo" :src="dataForm.logo" class="avatar" />
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
      </el-form-item>
      <el-form-item label="房间设施">
        <el-checkbox-group v-model="dataForm.facilities">
          <el-checkbox v-for="(fac, index) in facility" :label="fac.name">{{ fac.name }}</el-checkbox>
        </el-checkbox-group>
      </el-form-item>
      <el-form-item label="窗户" prop="windows">
        <el-radio v-model="dataForm.windows" label="0">没有</el-radio>
        <el-radio v-model="dataForm.windows" label="1">有</el-radio>
      </el-form-item>
      <el-form-item label="楼层" prop="floor"><el-input v-model="dataForm.floor" placeholder="楼层"></el-input></el-form-item>
      <el-form-item label="可住人数" prop="people"><el-input v-model="dataForm.people" placeholder="可住人数"></el-input></el-form-item>
      <el-form-item label="房间面积 " prop="area"><el-input v-model="dataForm.area" placeholder="房间面积 "></el-input></el-form-item>
      <el-form-item label="床型尺寸" prop="size"><el-input v-model="dataForm.size" placeholder="床型尺寸"></el-input></el-form-item>
      <el-form-item label="数量" prop="totalNum"><el-input v-model="dataForm.totalNum" placeholder="数量"></el-input></el-form-item>
      <el-form-item label="取消规则" prop="cancelTime">
        <el-row>
          <el-col class="form-item-row">
            <el-radio v-model="dataForm.cancelRule" label="1">入住当天</el-radio>
            <el-time-select
              class="el-input"
              v-model="dataForm.cancelTime"
              :picker-options="{
                start: '00:00',
                step: '00:01',
                end: '23:59'
              }"
              :default-value="dataForm.cancelTime"
              placeholder="选择时间"
            ></el-time-select>
            <span class="el-span">前可取消</span>
          </el-col>
        </el-row>
        <el-row>
          <el-col class="form-item-row">
            <el-radio v-model="dataForm.cancelRule" label="2">入住前&nbsp;&nbsp;&nbsp;&nbsp;</el-radio>
            <el-input-number class="el-input" v-model="dataForm.cancelDayNum" :min="1" :max="10" label="天"></el-input-number>
            <span class="el-span">天</span>
            <el-time-select
              class="el-input"
              v-model="dataForm.cancelTime"
              :picker-options="{
                start: '00:00',
                step: '00:01',
                end: '23:59'
              }"
              :default-value="dataForm.cancelTime"
              placeholder="选择时间"
            ></el-time-select>
            <span class="el-span">前可取消</span>
          </el-col>
        </el-row>
        <el-row>
          <el-col class="form-item-row">
            <el-radio v-model="dataForm.cancelRule" label="3">入住前&nbsp;&nbsp;&nbsp;&nbsp;</el-radio>
            <el-input-number class="el-input" v-model="dataForm.cancelDayNum" :min="1" :max="10" label="天"></el-input-number>
            <span class="el-span">天</span>
            <el-time-select
              class="el-input"
              v-model="dataForm.cancelTime"
              :picker-options="{
                start: '00:00',
                step: '00:01',
                end: '23:59'
              }"
              :default-value="dataForm.cancelTime"
              placeholder="选择时间"
            ></el-time-select>
            <span class="el-span">前可取消,收取</span>
            <el-input-number class="el-input" v-model="dataForm.deductScale" :min="1" :max="100" label="%"></el-input-number>
            <span class="el-span">%罚金，此后不可取消</span>
          </el-col>
        </el-row>
        <el-row><el-radio v-model="dataForm.cancelRule" label="4">不可取消</el-radio></el-row>
        <el-row><el-radio v-model="dataForm.cancelRule" label="0">可取消</el-radio></el-row>
      </el-form-item>
      <el-form-item label="图片" prop="img">
        <div class="updaloe-row">
          <el-upload
            class="avatar-uploader"
            :action="uploadAction"
            multiple
            ref="upload"
            :auto-upload="true"
            :show-file-list="true"
            list-type="picture-card"
            :file-list="fileList"
            :on-success="handleImageSuccess"
            :before-upload="beforeAvatarUpload"
            :on-change="handleOnCHange"
            :on-remove="handleRemove"
          >
            <i class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
          <!-- <el-button style="margin-left: 10px;" size="small" type="success" @click="submitUpload">上传到服务器</el-button> -->
        </div>
      </el-form-item>
      <el-form-item label="描述" style="height:300px" prop="description">
        <!-- <el-input v-model="dataForm.introduction" placeholder="酒店介绍"></el-input> -->
        <quill-editor
          style="height:200px"
          class="editor"
          v-model="dataForm.description"
          ref="myQuillEditor"
          :options="editorOption"
          @blur="onEditorBlur($event)"
          @focus="onEditorFocus($event)"
          @change="onEditorChange($event)"
        ></quill-editor>
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false">{{ $t('Common.Cancel') }}</el-button>
      <el-button v-if="dataForm.trialPictureState == 1" disabled>待审核</el-button>
      <el-button v-if="dataForm.trialPictureState == 2" type="primary" @click="dataFormSubmit()">{{ $t('Common.Confirm') }}</el-button>
      <el-button v-if="dataForm.trialPictureState == 3" type="primary" @click="dataFormSubmit()">重新提交</el-button>
    </span>
  </el-dialog>
</template>

<script>
export default {
  data() {
    return {
      inputVisible: false,
      inputValue: '',
      visible: false,
      editorOption: {
        placeholder: '请填写房间描述!'
      },
      uploadAction: '',
      dialogImageUrl: '',
      dialogVisible: false,
      fileList: [],
      facility: [],
      result: [],
      dataForm: {
        id: 0,
        trialPictureState:2,
        sellerId: '',
        sign: '',
        checkList:['全天房'],
        facility: [],
        cancelRule: '0',
        cancelDayNum: 1,
        cancelTime: '',
        deductTime: '',
        deductScale: 10,
        name: '',
        discounts: '',
        price: '',
        area: '',
        oprice: '',
        img: '',
        floor: '',
        people: 1,
        bed: '',
        breakfast: '',
        facilities: [],
        tagList: [],
        windows: '0',
        logo: '',
        size: '',
        isRefund: '',
        totalNum: 1,
        yjState: '',
        yjCost: '',
        sort: '',
        state: '',
        classify: 1
      },
      dataRule: {
        name: [
          {
            required: true,
            message: '房型名字不能为空',
            trigger: 'blur'
          }
        ],
        oprice: [
          {
            required: true,
            message: '门市价不能为空',
            trigger: 'blur'
          }
        ],
        size: [
          {
            required: true,
            message: '床型尺寸不能为空',
            trigger: 'blur'
          }
        ],
        area: [
          {
            required: true,
            message: '房间面积不能为空',
            trigger: 'blur'
          }
        ],
        sort: [{ required: true, message: '排序不能为空', trigger: 'blur' }],
        state: [
          {
            required: true,
            message: '房间状态不能为空',
            trigger: 'blur'
          }
        ],
        classify: [
          {
            required: true,
            message: '房间类别不能为空',
            trigger: 'blur'
          }
        ]
      }
    };
  },
  methods: {
    async submitUpload() {
      await this.$refs.upload.submit();
    },
    getFacility() {
      this.$http({
        url: this.$http.adornUrl(`/hotel/hotelfacility/list`),
        method: 'get',
        params: this.$http.adornParams({
          type: 2
        })
      }).then(({ data }) => {
        this.facility = data.page.list;
      });
    },
    onEditorBlur() {},
    onEditorFocus() {
      //获得焦点事件
    },
    onEditorChange() {
      //内容改变事件
    },
    init(id) {
      Object.assign(this.$data, this.$options.data());
      this.getFacility();
      this.fileList = [];
      this.uploadAction = this.$http.adornUrl(`/sys/oss/upload?token=${this.$cookie.get('token')}`);
      this.dataForm.id = id || 0;
      this.visible = true;
      this.$nextTick(() => {
        this.$refs['dataForm'].resetFields();
        this.dataForm.tagList = [];
        if (this.dataForm.id) {
          this.$http({
            url: this.$http.adornUrl(`/hotel/hotelroom/info/${this.dataForm.id}`),
            method: 'get',
            params: this.$http.adornParams()
          }).then(({ data }) => {
            if (data && data.code === 0) {
              this.dataForm.id = data.hotelroom.id;
              this.dataForm.facilities = data.hotelroom.facilities ? data.hotelroom.facilities.split(',') : [];
              this.dataForm.description = data.hotelroom.description;
              this.dataForm.name = data.hotelroom.name;
              this.dataForm.sellerId = data.hotelroom.sellerId;
              this.dataForm.sign = data.hotelroom.sign;
              this.dataForm.price = data.hotelroom.price;
              this.dataForm.oprice = data.hotelroom.oprice;
              this.dataForm.img = data.hotelroom.img;
              this.dataForm.floor = data.hotelroom.floor;
              this.dataForm.people = data.hotelroom.people;
              this.dataForm.bed = data.hotelroom.bed;
              this.dataForm.breakfast = data.hotelroom.breakfast === 1;
              this.dataForm.discounts = data.hotelroom.discounts === 1;
              this.dataForm.windows = data.hotelroom.windows + '';
              this.dataForm.logo = data.hotelroom.logo;
              this.dataForm.totalNum = data.hotelroom.totalNum;
              this.dataForm.uniacid = data.hotelroom.uniacid;
              this.dataForm.size = data.hotelroom.size;
              this.dataForm.area = data.hotelroom.area;
              this.dataForm.sort = data.hotelroom.sort;
              this.dataForm.checkList = data.hotelroom.checkList || [];
              this.dataForm.tagList = data.hotelroom.tagList || [];
              this.dataForm.state = data.hotelroom.state;
              this.dataForm.classify = data.hotelroom.classify;
              this.dataForm.rzTime = data.hotelroom.rzTime;
              this.dataForm.cancelRule = data.hotelroom.cancelRule + '';
              if (data.hotelroom.cancelRule == null) {
                this.dataForm.cancelRule = '0';
              }
              this.dataForm.trialPictureState = data.hotelroom.trialPictureState,
              this.dataForm.trialMsg = data.hotelroom.trialMsg,
              this.dataForm.cancelDayNum = data.hotelroom.cancelDayNum;
              this.dataForm.cancelTime = data.hotelroom.cancelTime;
              this.dataForm.deductTime = data.hotelroom.deductTime;
              this.dataForm.deductScale = data.hotelroom.deductScale;
              data.hotelroom.img.split(',').forEach(element => {
                if (element) {
                  this.fileList.push({ url: element });
                }
              });
              this.$forceUpdate();
            }
          });
        }
      });
    },
    // 表单提交
    async dataFormSubmit() {
      // await this.$refs.upload.submit();
      let icons = [];
      if (this.dataForm.facilities) {
        icons = this.dataForm.facilities
          .filter(f => f && f !== '')
          .map(f => {
            const fac = this.facility.find(i => i.name === f);
            return fac ? fac.icon : '';
          });
      }
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          this.$http({
            url: this.$http.adornUrl(`/hotel/hotelroom/${!this.dataForm.id ? 'save' : 'update'}`),
            method: 'post',
            data: this.$http.adornData({
              id: this.dataForm.id || undefined,
              facilities: this.dataForm.facilities
                .filter(f => f && f !== '')
                .reduce((p, n) => {
                  p += n + ',';
                  return p;
                }, ''),
              facilitiesIcon: icons.reduce((p, n) => {
                p += n + ',';
                return p;
              }, ''),
              description: this.dataForm.description,
              sellerId: this.dataForm.sellerId,
              sign: this.dataForm.sign,
              name: this.dataForm.name,
              price: this.dataForm.price,
              oprice: this.dataForm.oprice,
              img: this.dataForm.img,
              floor: this.dataForm.floor,
              people: this.dataForm.people,
              bed: this.dataForm.bed,
              breakfast: this.dataForm.breakfast ? 1 : 0,
              discounts: this.dataForm.discounts ? 1 : 0,
              windows: this.dataForm.windows,
              tagList: this.dataForm.tagList,
              checkList: this.dataForm.checkList,
              logo: this.dataForm.logo,
              totalNum: this.dataForm.totalNum,
              uniacid: this.dataForm.uniacid,
              size: this.dataForm.size,
              area: this.dataForm.area,
              isRefund: this.dataForm.isRefund,
              yjState: this.dataForm.yjState,
              yjCost: this.dataForm.yjCost,
              sort: this.dataForm.sort,
              state: this.dataForm.state,
              classify: this.dataForm.classify,
              rzTime: this.dataForm.rzTime,
              cancelRule: this.dataForm.cancelRule,
              cancelDayNum: this.dataForm.cancelDayNum,
              cancelTime: this.dataForm.cancelTime,
              deductTime: this.dataForm.deductTime,
              deductScale: this.dataForm.deductScale
            })
          }).then(({ data }) => {
            if (data && data.code === 0) {
              this.$message({
                message: this.$t('Common.OperationSuccessful'),
                type: 'success',
                duration: 1500,
                onClose: () => {
                  this.visible = false;
                  // 提交后晴空图片列表 以防再次打开时闪现
                  this.fileList = [];
                  this.$emit('refreshDataList');
                }
              });
            } else {
              this.$message.error(data.msg);
            }
          });
        }
      });
    },
    handleAvatarSuccess(res, file) {
      this.dataForm.logo = res.url;
    },
    handleImageSuccess(res, file, fileList) {
      let url = [];
      // 对于新增操作
      fileList.forEach(item => {
        const { response } = item;
        if (response && response.code === 0 && response.msg === 'success') {
          url.push(response.url);
        }
      });
      // 对于修改操作
      if (this.dataForm.id) {
        const imgs = this.dataForm.img.split(',');
        url = [...url, ...imgs];
      }
      this.dataForm.img = url.join(',');
    },
    handleClose(tag) {
      this.dataForm.tagList.splice(this.dataForm.tagList.indexOf(tag), 1);
    },

    showInput() {
      this.inputVisible = true;
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus();
      });
    },

    handleInputConfirm() {
      let inputValue = this.inputValue;
      if (inputValue) {
        this.dataForm.tagList.push(inputValue);
      }
      this.inputVisible = false;
      this.inputValue = '';
    },
    handleOnCHange(file, fileList) {},
    handleRemove(file, fileList) {
      /**
       * handleRemove只针对修改操作，对已存在的图片进行删除，新增实际上可以不定义此函数
       * 以下条件说明：
       * 用于限制已经上传的图片是否可被删除
       * 去掉注释则为：以前上传的图片不允许在修改进行删除
       * file.status：success已经上传到服务器的图片
       * file.status：ready从硬盘读取但是未上传到服务器的图片
       */
      // if (file.status === 'success') return;
      // uid可能相同，但是url基本不可能相同，但了保险，做一个"&&"操作
      const index = this.fileList.findIndex(item => item.uid === file.uid && item.url === file.url);
      // 针对已经上传了的图片进行删除掉，同时更新this.dataForm.img，以便“真正的删除”
      if (this.dataForm.id && index > -1) {
        this.fileList.splice(index, 1);
        const url = [];
        this.fileList.map(item => {
          url.push(item.url);
        });
        this.dataForm.img = url.join(',');
      }
      // 删除图片并更新列表
      this.fileList = fileList;
    },
    beforeAvatarUpload(file) {
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!');
      }
      return isLt2M;
    }
  }
};
</script>
<style lang="less">
.hotel-room {
  .el-dialog__body {
    height: 80vh;
  }
  .label-color {
    color: red;
  }
  .form-item-row {
    margin-bottom: 12px;
  }
  .el-input {
    width: 120px;
  }
  .el-span {
    padding: 0 5px;
  }
}
</style>
<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 148px;
  height: 148px;
  line-height: 148px;
  text-align: center;
}
.avatar {
  width: 148px;
  height: 148px;
  display: block;
}
.updaloe-row {
  display: flex;
  align-items: center;
}
.el-tag + .el-tag {
  margin-left: 10px;
}
.button-new-tag {
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}
.input-new-tag {
  width: 190px;
  margin-left: 10px;
  vertical-align: bottom;
}
</style>
<style lang="scss" scoped>
.el-dialog__wrapper /deep/ .el-dialog {
  width: 80%;
}
@media only screen and (max-width: 1180px) {
  .el-dialog__wrapper /deep/ .el-dialog {
    width: 100%;
  }
}  
</style>